import { _decorator, Label, Sprite } from 'cc';
import { app } from 'db://app-game/core/app';
import { AsyncQueue, NextFunction } from 'db://app-game/libs/collection/AsyncQueue';
import { ecs } from 'db://app-game/libs/ecs/ECS';
import { CCComp } from 'db://app-game/module/common/CCComp';
import { GameEvent } from '../../../../common/config/GameEvent';
import { UIID } from '../../../../common/config/GameUIConfig';
import { Load } from '../Load';

const { ccclass, property } = _decorator;

/** 游戏资源加载 */
@ccclass('LoadingViewComp')
@ecs.register('LoadingView', false)
export class LoadingViewComp extends CCComp {
  @property({ type: Label, tooltip: '加载进度条提示文本' })
  promptLabel: Label = null!;
  @property({ type: Sprite, tooltip: '加载进度条' })
  progress: Sprite = null!;

  /** 加载实例 */
  loadEntity: Load = null!;

  /** 加载完成数 */
  finished: number = 0;
  /** 加载总数 */
  total: number = 0;
  /** 跳转到的界面id */
  toUiid: UIID | -1 = -1;
  protected start(): void {
    /** 加载实列 */
    this.loadEntity = this.ent as Load;
    this.toUiid = this.loadEntity.LoadDataModel.uiid;

    let queue: AsyncQueue = new AsyncQueue();
    // 1.注册事件
    this.addEvent();
    // 2.加载资源
    this.loadRes(queue);

    // 3.加载完成事件
    this.onCompleteCallback(queue);
  }
  private addEvent() {
    this.on(GameEvent.SceneChangeComplete, this.onHandler, this);
  }

  private onHandler(event: string) {
    switch (event) {
      case GameEvent.SceneChangeComplete:
        // 加载流程结束，移除加载提示界面
        this.ent.remove(LoadingViewComp);
        break;
    }
  }
  /** 加载资源 */
  private loadRes(queue: AsyncQueue) {
    const { loadPaths } = this.loadEntity.LoadDataModel;
    for (let i = 0; i < loadPaths.length; i++) {
      queue.push((next: NextFunction) => {
        const { text, path } = loadPaths[i];
        this.progress.fillRange = 0;
        this.promptLabel.string = text;
        app.res.loadDir(path, this.onProgressCallback.bind(this), next);
      });
    }
    // 开始
    queue.play();
  }

  /** 加载进度事件 */
  private onProgressCallback(finished: number, total: number) {
    this.finished = finished;
    this.total = total;

    let progress = finished / total;
    if (progress > this.progress.fillRange) {
      this.progress.fillRange = progress;
    }
  }

  /** 加载完成事件 */
  private onCompleteCallback(queue: AsyncQueue) {
    queue.complete = async () => {
      // 1.通知界面初始化布局
      this.loadEntity.LoadDataModel.sceneEnt.initLayout();
    };
  }

  /** 重置 */
  reset(ent: Load): void {
    setTimeout(async () => {
      // 1.关闭加载界面
      app.gui.remove(UIID.Loading);
      // 2.打开游戏主界面(自定义逻辑)
      let node = await app.gui.openAsync(this.toUiid);
      if (node) {
        ent.LoadDataModel.jumpCompleted(node);
      }
      // 3.清空加载资源列表
      this.toUiid = -1;
    }, 500);
  }
}
